import { use } from 'echarts/core';
import { PieChart } from 'echarts/charts';
import { TooltipComponent, LegendComponent, GridComponent } from 'echarts/components';
// import { divide, multiply, numThousandthFilter } from '@numa/common/utils/math';
import { TDescLegend, TPieDataItem, TPieSize } from './types';
import { PropType } from 'vue';
import { EChartsOption } from 'echarts';
import DescLegend, { TDescLegendPrimaryValueType } from './DescLegend';
import { MciEcharts } from '@/components/base/Echarts';
import './index.scss';

use([TooltipComponent, LegendComponent, PieChart, GridComponent]);

export default defineComponent({
  props: {
    size: {
      type: String as PropType<TPieSize>,
      default: 'default'
    },
    option: {
      type: Object as PropType<EChartsOption>,
      default: () => ({})
    },
    scale: {
      type: Number,
      default: 1
    },
    primaryValueType: {
      type: String as PropType<TDescLegendPrimaryValueType>,
      default: 'QUANTITY'
    }
  },
  setup(props, { slots }) {
    const { option } = toRefs(props);
    const descLegendData = ref<TDescLegend[]>([]);

    const calculateLegendData = (data: TPieDataItem[], colors: string[]) => {
      const total = data?.reduce((prev, cur) => {
        return prev + cur.value;
      }, 0);

      return data?.map((item, index) => {
        return {
          label: item?.name,
          color: colors[index],
          // values: [
          //   `${props.primaryValueType==='AMOUNT'?numThousandthFilter(item.value, '0,0.00'):numThousandthFilter(item.value, '0,0')} ${item.unit ?? ''}`,
          //   Number(multiply(divide(item.value, total), 100)).toFixed(2) + '%'
          // ]
          values: [
            `${props.primaryValueType === 'AMOUNT' ? item.value : item.value} ${item.unit ?? ''}`,
            (item.value / total).toFixed(2) + '%'
          ]
        } as TDescLegend;
      });
    };

    watch(
      option,
      (opt) => {
        const data = opt.series?.[0].data as TPieDataItem[];
        descLegendData.value = calculateLegendData(data, option.value.color || []);
      },
      {
        immediate: true
      }
    );

    return () => (
      <div class={['flex items-top justify-between  w-full', `pie-chart--${props.size}`]}>
        <div class="pt-30px">
          <div class="pie-chart-wrapper" style={{ transform: `scale(${props.scale})` }}>
            <div class="circle-wrapper">
              <div class="circle-content"></div>
            </div>
            <MciEcharts class="w-full h-full" option={option.value} />
          </div>
        </div>
        {slots.legend ? (
          slots.legend()
        ) : (
          <DescLegend legendData={descLegendData.value} size={props.size} primaryValueType={props.primaryValueType} />
        )}
      </div>
    );
  }
});
